#include "timer.hpp"
#include "os.hpp"

#ifdef NMC_WIN32

#include <windows.h>

static unsigned long long currentTick = 0;

void initTimer()
{
	unsigned int period = 1;
	
	while ( timeBeginPeriod( period ) != TIMERR_NOERROR )
	{
		period++;
	}  
}

unsigned long getTick()
{
	static DWORD lastTime = timeGetTime();
	DWORD time = timeGetTime();	
	unsigned long diff = time - lastTime;
	lastTime = time;
	currentTick += diff;
	return long( ( currentTick * TICKS_PER_SECOND ) / 1000 );
}

#else // NOT WIN32

#include <allegro.h>

static volatile long currentTick = 0;

static void timerCallback()
{
	++currentTick;
}
END_OF_FUNCTION(timerCallback)

long getTick()
{
	return currentTick;
}

void initTimer()
{
	install_timer();
	LOCK_VARIABLE(currentTick);
	LOCK_FUNCTION(timerCallback);
	install_int_ex(timerCallback, BPS_TO_TIMER(TICKS_PER_SECOND));
}

#endif